package com.mes.scheduler.task;

import com.mes.utils.DBConctionQuery;
import com.yy.base.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SchedulerRun implements Runnable {
	private String taskId = null;
	private String caseSql = null;
	private String facType = null;
	private int runCycle = 0;
	private String lowerVal = null;//下限值
	private String upperVal = null;//上限值
	Map<String, String> resultMap = null;
//	private boolean dcPoint = false;
	private DBConctionQuery query = null;
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public SchedulerRun(Map<String, Object> map) {
		//id, Name, Case_Sql, run_cycle, dc_point, Facilities_type
		taskId = (String)map.get("ID");
		caseSql = (String)map.get("CASE_SQL");
		facType = (String)map.get("FACILITIES_TYPE");
		runCycle = Integer.parseInt(map.get("RUN_CYCLE") + "");
		lowerVal = (String)map.get("LOWER_VAL");
		upperVal = (String)map.get("UPPER_VAL");
//		dcPoint = "Y".equals(map.get("DC_POINT"));
	}
	
	@Override
    public void run() {
		try {
			query = new DBConctionQuery();
			
			//获取数据源
			String sql = "select Code, Name, Sql, Params from Emes_Task_Scheduler_Source where sql is not null and Emes_Task_Scheduler_Id = ?";
			List<Map<String, Object>> sources = query.query(sql, taskId);
			
			//获取所有结果
			sql = "select Result, Exe_Sql from Emes_Task_Scheduler_Result where Exe_Sql is not null and Emes_Task_Scheduler_Id = ?";
			List<Map<String, Object>> results = query.query(sql, taskId);
			resultMap = new HashMap<String, String>();
			for (Map<String, Object> map : results) {
				resultMap.put((String)map.get("RESULT"), (String)map.get("EXE_SQL"));
			}
			
			//判断是否从设备点表中获取采集数据
			if (facType != null) {
				//获取所有设备类型
				List<Map<String, Object>> list = query.query("select f.Eam_Facilities_Id id, f.status, f.ad_org_id, f.name, f.code, f.short_CODE " +
						"from Eam_Facilities f where f.fancility_type = ?", facType);
				if (list != null && !list.isEmpty()) {
					for (Map<String, Object> map : list) {
						execute(sources, map);
					}
				}
			} else {
				execute(sources, null);
			}
			query.commit();
		} catch (Exception e) {
			query.rollback();
			e.printStackTrace();
		}
		//更新任务状态为完成，根据定时周期，计算下次执行时间
		try {
			String sql = "update Emes_Task_Scheduler set status = 'STOP', " +
					"Next_Run_Time = (sysdate + ? / (24 * 60)) " +
					"where Emes_Task_Scheduler_Id = ?";
			query.execute(sql, runCycle, taskId);
			query.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		query.close();
		query = null;
    }
	
	//获取数据源数据，执行逻辑语句，获取执行结果
	private void execute(List<Map<String, Object>> sources, Map<String, Object> facMap) throws SQLException {
		Map<String, Object> value = new HashMap<String, Object>();
		String sql = null;
		Map<String, Object> data = null;
		Map<String, Object> params = new HashMap<String, Object>();
		
		for (Map<String, Object> map : sources) {
			params.clear();
			sql = (String)map.get("SQL");
			
			if ((sql.indexOf(":facilitiesId") > -1 || sql.indexOf(":facId") > -1) && facMap != null) {
				data = query.queryUnique(sql.replace(":facilitiesId", "?").replace(":facId", "?"), facMap.get("ID"));
			} else {
//				System.out.println(taskId+"--获取参数值--"+sql);
				data = query.queryUnique(sql);
			}
			if (data == null) {
				return;
			}
			value.putAll(data);
		}
		sql = "select " + caseSql + " data from dual";
		Object val = null;
		for (String key : value.keySet()) {
			val = value.get(key);
			if (val instanceof Date) {
				sql = sql.replaceAll("@" + key + "@", "to_Date('" + sdf.format((Date)value.get(key)) + "', 'yyyy-MM-dd HH24:mi:ss')");
			} else if (val instanceof java.sql.Timestamp) {
				sql = sql.replaceAll("@" + key + "@", "to_Date('" + sdf.format((java.sql.Timestamp)value.get(key)) + "', 'yyyy-MM-dd HH24:mi:ss')");
			} else {
				sql = sql.replaceAll("@" + key + "@", "'" + value.get(key) + "'");
			}
		}
		//判断上下限值
		if(StringUtils.isNotEmpty(lowerVal)){
			sql = sql.replaceAll("@下限@", "'" + lowerVal + "'");
		}
		if(StringUtils.isNotEmpty(upperVal)){
			sql = sql.replaceAll("@上限@", "'" + upperVal + "'");
		}
//		System.out.println(taskId+"--判断--"+sql);
		data = query.queryUnique(sql);
		if (data != null) {
			executeResult(String.valueOf(data.get("DATA")), facMap,value);
		}
	}
	
	private void executeResult(String result, Map<String, Object> facMap, Map<String, Object> valMap) throws SQLException {
		if (resultMap.containsKey(result)) {
			String sql = resultMap.get(result);
			if (sql != null) {
				if (facMap != null) {
					for (String key : facMap.keySet()) {
						sql = sql.replaceAll("@" + key + "@", facMap.get(key) + "");
					}
				}
				if(valMap!=null){
					for (String key : valMap.keySet()) {
						sql = sql.replaceAll("@" + key + "@", "'" + valMap.get(key) + "'");
					}
				}
				String []sqls = sql.split(";");
				for (String str : sqls) {
					if (!StringUtil.isBlank(str)) {
//						System.out.println(taskId+"---"+str);
						query.execute(str);
					}
				}
			}
		}
	}
}